package com.mf.controller.admin;

import com.mf.entity.GoodsAttribute;
import com.mf.entity.Log;
import com.mf.service.GoodsAttributeService;
import com.mf.service.LogService;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/goodsAttribute")
public class GoodsAttributeController {

    @Resource
    private GoodsAttributeService goodsAttributeService;

    @Resource
    private LogService logService;

    @RequestMapping("/list")
    public Map<String, Object> getGoodsSpecList(GoodsAttribute goodsAttribute, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "rows", required = false) Integer rows ) throws Exception{
        Map<String, Object>  result = new HashMap<>();
        List<GoodsAttribute> goodsSpeList = goodsAttributeService.list(goodsAttribute, page, rows, Sort.Direction.ASC, "id");
        Long goodsSpecCount = goodsAttributeService.getCount(goodsAttribute);
        result.put("rows", goodsSpeList);
        result.put("total", goodsSpecCount);
        logService.save(new Log(Log.SEARCH_ACTION, "查询SKU商品属性信息"));
        return result;
    }

    @RequestMapping("/save")
    public Map<String, Object> save(GoodsAttribute goodsAttribute) throws Exception{
        Map<String, Object> result = new HashMap<>();

        if(goodsAttribute.getId() != null){
            logService.save(new Log(Log.UPDATE_ACTION, "更新sku商品属性"+goodsAttribute));
        }else{
            logService.save(new Log(Log.ADD_ACTION, "添加sku商品属性" + goodsAttribute));
        }
        goodsAttributeService.save(goodsAttribute);
        result.put("success", true);
        return result;
    }

    @RequestMapping("/delete")
    public Map<String, Object> delete(String ids) throws Exception{
        Map<String, Object> resultMap = new HashMap<>();

        String[] idsStr = ids.split(",");
        for(int i = 0; i < idsStr.length; i++){
            int id = Integer.parseInt(idsStr[i]);
            logService.save(new Log(Log.UPDATE_ACTION, "删除sku商品属性 id:" + id));
            goodsAttributeService.delete(id);
        }

        resultMap.put("success", true);
        return resultMap;
    }

}
